package com.specter.utils;

import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Locale;

import freemarker.cache.MruCacheStorage;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;

/**
 * Note: Freemarker模板工具类
 * 
 * @author Liang.Wang
 * @version Mar 2, 2017
 */
@Slf4j
public class FreemarkerUtils {
	private FreemarkerUtils() {
		throw new IllegalStateException("Utility class");
	}

	private static Configuration cfg;
	private static final String UTF8 = "UTF-8";

	static {
		cfg = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
		cfg.setCacheStorage(new MruCacheStorage(20, 250));
		cfg.setLocale(Locale.CHINA);
		cfg.setDefaultEncoding(UTF8);
		cfg.setObjectWrapper(new DefaultObjectWrapper(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS));
		cfg.setNumberFormat("0.######");
	}

	public static String render(String template, Object dataModel) {
		try {
			if (template.startsWith("dir:")) {// 使用dir:来从项目中获取路径
				template = template.substring(template.indexOf("dir:") + 4);
				cfg.setDirectoryForTemplateLoading(new File(System.getProperty("user.dir")));
			} else {
				cfg.setClassForTemplateLoading(FreemarkerUtils.class, "/");
			}
		} catch (IOException e1) {
			e1.printStackTrace();
		}

		// if (log.isDebugEnabled()) {
		// 	String sb = ToStringBuilder.reflectionToString(dataModel);
		// 	log.debug("dataModel:{}", sb);
		// }

		StringWriter stringWriter = new StringWriter();
		BufferedWriter writer = new BufferedWriter(stringWriter);

		String html = "";
		try {
			Template temp = cfg.getTemplate(template);
			temp.process(dataModel, writer);
			writer.flush();

			html = stringWriter.toString();
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		} finally {
			if (writer != null) {
				try {
					writer.close();
				} catch (Exception e) {
					log.error(e.getMessage(), e);
				}
			}
		}
		return html;
	}
}
